package com.qf.controller;


import com.qf.constant.SsmModelConstant;
import com.qf.entity.User;
import com.qf.enums.ErrorMsgEnums;
import com.qf.exception.SsmModelException;
import com.qf.service.UserService;
import com.qf.util.SendUtil;
import com.qf.util.StringUtils;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.xml.transform.Result;

@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SendUtil sendUtil;

    //展示注册页面
    @GetMapping("/register-ui")
    public String registerUI(){

        return "user/register";

    }

    //异步检验用户名
    @PostMapping("/check")
    @ResponseBody
    public ResultVO checkUsername(@RequestBody User user){

        userService.checkUsername(user.getUsername());

        return new ResultVO(0,"该用户名可用",null);
    }

    //发送短信验证
    @PostMapping("/send")
    @ResponseBody
    public ResultVO send(String phone, HttpSession session){

        if (phone==null || phone.trim().length()==0){
            log.error("【发送短信验证码】 电话格式有误！ phone={}",phone);
            throw new SsmModelException(ErrorMsgEnums.PACKAGE_PARAMETERS_ERROR.getCode(),"电话格式有误！");
        }

        ResultVO vo = sendUtil.sendmsg(phone, session);
        return vo;
    }

    //用户注册
    @PostMapping("/register")
    @ResponseBody
    public ResultVO register(@Valid User user,String registerCode,HttpSession session){
        String trueCode = (String) session.getAttribute(SsmModelConstant.USER_CODE);
        if (registerCode==null || !registerCode.equals(trueCode)){
            log.info("【注册用户】验证码输入有误！ user={}，registerCode={}",user,registerCode);
            throw new SsmModelException(ErrorMsgEnums.PACKAGE_PARAMETERS_ERROR.getCode(),"验证码输入有误！");
        }

        userService.register(user);
        return new ResultVO(0,"注册成功",null);

    }

    //用户登录页面
    @GetMapping("/login-ui")
    public String loginUI(){

        return "user/login";

    }

    //用户登录
    @PostMapping("/login")
    @ResponseBody
    public ResultVO login(String username,String password,HttpSession session){
        if (StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            log.info("【用户登录】登录参数有误！ username={} password={}",username,password);
            throw new SsmModelException(ErrorMsgEnums.PACKAGE_PARAMETERS_ERROR.getCode(),"用户名或密码输入有误！");
        }
        User loginUser = userService.login(username, password);
        session.setAttribute(SsmModelConstant.USER_INFO,loginUser);

        return new ResultVO(0,"登录成功",null);
    }
}
